import axios from 'axios'
import router  from '@/router'
import store from "@/store"
const globalProps = window.$vueApp.config.globalProperties
globalProps.$axios = axios
// globalProps.BASE_URL = `http://${process.env.NODE_ENV === 'dev' ? 'localhost' : '106.13.16.28'}:10000`
globalProps.BASE_URL = '/api'
console.log("注入请求地址", axios.defaults, store)
const service = axios.create({
  // baseURL: 'http://api.gdsft.com/',
  baseURL: '/api',
  timeout: 50000,
  headers:{
    'Authorization': 'Bearer',
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods":"*",
    "Access-Control-Allow-Credentials": true,
    'RequestStamp':"",
  }
})

service.defaults.withCredentials = true // 让ajax携带cookie
service.interceptors.request.use(
  cfg => {
		if (store.state.token) {
			if(store.state.token!='null'){
				cfg.headers.token = `${store.state.token}`;
				cfg.headers.RequestStamp=Date.parse(new Date().toString());
			}
		}
    
		return cfg
	},
  
  // eslint-disable-next-line handle-callback-err
  (error) => {
    return Promise.reject(error)
  }
)

function isJSON(val) {
  if (typeof val !== 'string') {
    return false
  }
  try {
    const obj = JSON.parse(val)
    if (Object.prototype.toString.call(obj) === '[object Object]') {
      return true
    } else {
      return false
    }
  } catch (e) {
    return false
  }
}
service.interceptors.response.use(
  (response) => {
    if (response.headers && response.headers?.token) { //只用调用 公钥接口才会在响应体返回 token 其他接口一律不会返回token
      const token = response.headers.token;
      store.commit("setToken", token);
    }
    if (!response.succeed) {
      const code = response.status;
      switch (code) {
        //未登录
        case 402:
          //location.href = `${global.baseUserUrl}/login/login.html`;
          return;
        case 401:
          console.log("relaunch")
          store.commit("setToken", "")
          router.push('/login')
        case 503:
          console.log("relaunch 503")
          store.commit("setToken", "")
          router.push('/login')
        case 200:
          if (response.data.message == '无效的Token') {
            store.commit("setToken", "")
            router.push('/login')
          }
          default:
            break;
      }
    }
    return response
  },
  // 拦截异常的响应
  error => {
		if (error && error.response) {
      // const err = '未登录或登录状态已过期，请重新登录'
      // ElMessage({
      //   message: err,
      //   type: 'error'
      // })
			switch (error.response.status) {
				case 401:
					console.log("relaunch error",router)
					store.commit("setToken", "")
					router.push('/login')
				case 503:
					console.log("relaunch error 503",router)
					store.commit("setToken", "")
					router.push('/login')
			}
			if (error.response) {
				return Promise.reject(error.response.data)
			}
			return Promise.reject(error)
		} else {
			return Promise.reject(error)
		}
		
	}
)


export function syncRequest(config) {
  let ajax = new XMLHttpRequest()
  ajax.withCredentials = true
  //ajax.responseType = 'json'
  ajax.open(config.method, globalProps.BASE_URL + config.url, false)
  ajax.onload = function (e) {
    if (ajax.readyState === 4) {
      if (ajax.status === 200 && config.success) {
        config.success(ajax.responseText)
      } else if (config.fail) {
        config.fail(ajax.responseText)
      }
    }
  }
  ajax.onerror = function (e) {
    if (config.fail) {
      config.fail(ajax.responseText)
    }
  }
  if (config.data) {
    if (config.type === 'json') {
      ajax.setRequestHeader('Content-type', 'application/json')
      ajax.send(JSON.stringify(config.data))
    } else {
      ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
      let form = new FormData()
      for (const key in config.data) {
        form.set(key, config.data[key])
      }
      ajax.send(form)
    }
  } else {
    ajax.send(null)
  }
}

export default service